﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MREO.data;
using System.Diagnostics;
using System.Data.SqlServerCe;

namespace MREO.gui
{
    public partial class fPresent : Form
    {
        supportMethod supMeth = new supportMethod();

        Connection Conn = new Connection();
        SqlCeDataAdapter adapter = new SqlCeDataAdapter();
        SqlCeCommand command = null;

        Template templ = new Template();
        public int tabIndex;
        public string tabKey;
 
        public fPresent(Template pTempl)
        {
            templ = pTempl;

            InitializeComponent();

            if (pTempl._templ != null)
            {
                webBrowser_template.DocumentText = Encoding.UTF8.GetString(pTempl._templ);
                webBrowser_template.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_template_DocumentCompleted);
            }
        }

        void webBrowser_template_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            initTemplateParam(templ._id);
        }

        // Инициализируем параметры шаблона
        private void initTemplateParam(long pTemplId)
        {
            DataTable dt = new DataTable();
            try
            {
                Conn.con.Open();

                command = new SqlCeCommand("SELECT xname, xvalue " +
                                            " FROM templateParam WHERE mnuItems = @mnuItems"
                                            , Conn.con);
                command.Parameters.Add("@mnuItems", SqlDbType.NVarChar).Value = pTemplId;
                adapter.SelectCommand = command;
                adapter.Fill(dt);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
            finally
            {
                command.Dispose();
                adapter.Dispose();
                if (Conn.con.State == ConnectionState.Open)
                    Conn.con.Close();
            }

            // Вызваем методы заполняющие шаблон
            string xName;
            string xValue;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                xName = dt.Rows[i]["xvalue"].ToString();

                if (xName.Substring(0, 1).Equals("#")) // Глобальный параметр
                {
                    xName = xName.Substring(1, xName.Length - 1);
                    xValue = getGValParamValue(xName);
                }
                else
                {
                    xValue = xName;
                }

                webBrowser_template.Document.InvokeScript(dt.Rows[i]["xname"].ToString(), new object[] { xValue });
            }

        }

        private string getGValParamValue(string xName)
        {
            string xvalue = xName; // Если не найдется параметр вернется имч указанного параметра
            DataTable dt = new DataTable();

            try
            {
                Conn.con.Open();

                command = new SqlCeCommand("SELECT xvalue " +
                                            " FROM gval WHERE xname = @xname"
                                            , Conn.con);
                command.Parameters.Add("@xname", SqlDbType.NVarChar).Value = xName;
                adapter.SelectCommand = command;
                adapter.Fill(dt);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
            finally
            {
                command.Dispose();
                adapter.Dispose();
                if (Conn.con.State == ConnectionState.Open)
                    Conn.con.Close();
            }

            foreach (DataRow dr in dt.AsEnumerable())
            {
                xvalue = dr["xvalue"].ToString();
            }

            return xvalue;
        }

        private void toolStripButton_print_Click(object sender, EventArgs e)
        {
            webBrowser_template.ShowPrintPreviewDialog();

            try
            {
                supMeth.saveLogPrint(templ._name);
            }
            catch (Exception exc) { MessageBox.Show(exc.Message); }

        }

        private void toolStripButton_save_Click(object sender, EventArgs e)
        {
            webBrowser_template.ShowSaveAsDialog();
        }

        private void fPresent_Shown(object sender, EventArgs e)
        {
            //initTemplateParam(templ._id);
        }
    }
}
